package com.zksk.portal.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zksk.admin.api.RemoteFileService;
import com.zksk.admin.api.domain.SysFile;
import com.zksk.common.core.domain.R;
import com.zksk.common.core.web.controller.BaseController;
import com.zksk.common.security.utils.SecurityUtils;
import com.zksk.mbg.admin.domain.*;
import com.zksk.portal.domain.vo.*;
import com.zksk.portal.service.invoice.MemberInvoiceService;
import com.zksk.portal.service.member.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequestMapping("/member")
@RestController
@Api(tags = "企业信息相关接口")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberOperatorService memberOperatorService;
    @Autowired
    private MemberInvoiceService memberInvoiceService;
    @Autowired
    private MemberManageService memberManageService;
    @Autowired
    private MemberScoreService memberScoreService;
    @Autowired
    private MemberCredentialService memberCredentialService;
    @Autowired
    private CredentialLevelService credentialLevelService;
    @Autowired
    private RemoteFileService remoteFileService;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/upload")
    @SneakyThrows
    public R<SysFile> upload(@RequestPart("file") MultipartFile file) {
        R<SysFile> upload = remoteFileService.upload(file);
        return upload;
    }

    /**
     * 根据企业id查询企业信息
     */
    @GetMapping(value = "/member/{memberId}")
    @ApiOperation(value = "根据企业id查询企业信息")
    public R<MemberVo> selectMember(@PathVariable Long memberId) {
        MemberVo memberVo=new MemberVo();
        Member member = memberService.getById(memberId);
        //获取企业经办人信息
        QueryWrapper<MemberOperator> queryWrapper=new QueryWrapper<MemberOperator>()
                .eq("member_id",memberId);
        MemberOperator memberOperator = memberOperatorService.getOne(queryWrapper);
        memberVo.setMember(member);
        if(memberOperator!=null){
            memberVo.setMemberOperator(memberOperator);
        }
        return R.ok(memberVo);
    }
    /**
     * 保存企业信息
     */
    @PostMapping(value = "/save/member")
    @ApiOperation(value = "保存企业信息")
    public R saveMember(@RequestBody MemberVo memberVo){
        Boolean flag=memberService.saveMember(memberVo);
        if (flag){
            return R.ok("保存成功");
        }
        return R.fail("保存失败");
    }
    /**
     * 保存基本户信息
     */
    @PostMapping(value = "/save/bank")
    @ApiOperation(value = "保存基本户信息")
    public R saveBank(@RequestBody BankVo bankVo){
        Boolean flag=memberService.saveBank(bankVo);
        if (flag){
            return R.ok("保存成功");
        }
        return R.fail("保存失败");
    }

    /**
     * 根据企业id查询发票信息
     */
    @GetMapping(value = "/invoice/{memberId}")
    @ApiOperation(value = "根据企业id查询发票信息")
    public R<InvoiceVo> selectInvoice(@PathVariable Long memberId) {
        InvoiceVo invoiceVo = new InvoiceVo();
        //获取企业信息
        Member member = memberService.getById(memberId);
        //获取发票信息
        QueryWrapper<MemberInvoice> queryWrapper=new QueryWrapper<MemberInvoice>()
                .eq("member_id",memberId);
        MemberInvoice one = memberInvoiceService.getOne(queryWrapper);
        invoiceVo.setMember(member);
        invoiceVo.setMemberInvoice(one);
        return R.ok(invoiceVo);
    }
    /**
     * 保存发票信息
     */
    @PostMapping(value = "/save/invoice")
    @ApiOperation(value = "保存发票信息")
    public R save(@RequestBody MemberInvoice memberInvoice){
        if(memberInvoice.getMemberId()==null){
            return R.fail("保存发票信息失败,企业信息不能为空");
        }
        if (memberInvoice.getId()!=null){
            memberInvoice.setUpdateTime(null);
            memberInvoice.setUpdateBy(SecurityUtils.getUsername());
        }else{
            memberInvoice.setCreateBy(SecurityUtils.getUsername());
        }
        if (memberInvoiceService.saveOrUpdate(memberInvoice)){
            return R.ok("保存成功");
        }
        return R.fail("保存失败");

    }

    /**
     * 根据企业id查询经营信息
     */
    @GetMapping(value = "/manage/{memberId}")
    @ApiOperation(value = "根据企业id查询经营信息")
    public R<ManageVo> selectManage(@PathVariable Long memberId) {
        ManageVo manageVo = new ManageVo();
        //获取经营信息
        QueryWrapper<MemberManage> queryManage=new QueryWrapper<MemberManage>()
                .eq("member_id",memberId);
        MemberManage memberManage = memberManageService.getOne(queryManage);

        //获取业绩信息
        QueryWrapper<MemberScore> queryScore=new QueryWrapper<MemberScore>()
                .eq("member_id",memberId);
        List<MemberScore> listScore = memberScoreService.list(queryScore);

        //获取资质证书信息
        QueryWrapper<MemberCredential> queryCredential=new QueryWrapper<MemberCredential>()
                .eq("member_id",memberId);
        List<MemberCredential> listMemberCredentail = memberCredentialService.list(queryCredential);

        manageVo.setMemberManage(memberManage);
        manageVo.setMemberScoreList(listScore);
        manageVo.setMemberCredentialList(listMemberCredentail);
        return R.ok(manageVo);
    }

    /**
     * 新增和编辑资质证书
     */

    @PostMapping(value = "/credential")
    @ApiOperation(value = "新增和编辑资质证书")
    public R saveOrUpdateCredential(@RequestBody MemberCredential memberCredential){
        if (memberCredential.getId()!=null){
            memberCredential.setUpdateBy(SecurityUtils.getUsername());
        }else{
            memberCredential.setCreateBy(SecurityUtils.getUsername());
        }
        if (memberCredentialService.saveOrUpdate(memberCredential)){
            return R.ok("操作成功");
        }else{
            return R.fail("操作失败");
        }

    }
    /**
     * 新增和编辑业绩
     */

    @PostMapping(value = "/score")
    @ApiOperation(value = "新增和编辑业绩")
    public R saveOrUpdateScore(@RequestBody MemberScore memberScore){
        if (memberScore.getId()!=null){
            memberScore.setUpdateBy(SecurityUtils.getUsername());
        }else{
            memberScore.setCreateBy(SecurityUtils.getUsername());
        }
        if (memberScoreService.saveOrUpdate(memberScore)){
            return R.ok("操作成功");
        }else{
            return R.fail("操作失败");
        }

    }

    /**
     * 新增经营、审计、财务、流水信息
     * @param request
     * @return
     */
    @PostMapping(value = "/manage/upload")
    @ApiOperation(value = "新增经营、审计、财务、流水信息")
    public R<MemberManage> save(MultipartHttpServletRequest request){
        MultipartFile file = request.getFile("file");
        String memberManageVoStr = request.getParameter("memberManageVo");
        MemberManageVo memberManageVo = JSONObject.parseObject(memberManageVoStr, MemberManageVo.class);
        R<SysFile> upload = remoteFileService.upload(file);

        String fileName = "";
        if (upload.getCode() == R.SUCCESS) {
            fileName = upload.getData().getName();
        }else{
            return R.fail("上传文件失败");
        }
        Long memberId = memberManageVo.getMemberId();// 通过这个用户的id 查询出原来的信息

        MemberManage saveMemberManage = memberManageService.getOne(
                new QueryWrapper<MemberManage>()
                .eq("member_id", memberId)
                .orderByDesc("create_time")
        );

        String fileType = memberManageVo.getFileType();
        if (fileType.equals("1")) { // 公司章程
            saveMemberManage.setRules(fileName);
            saveMemberManage.setRulesTime(LocalDateTime.now());
        } else if(fileType.equals("2")){// 审计报告
            saveMemberManage.setAudit(fileName);
            saveMemberManage.setAuditTime(LocalDateTime.now());
        } else if(fileType.equals("3")){// 财务报表
            saveMemberManage.setFinance(fileName);
            saveMemberManage.setFinanceTime(LocalDateTime.now());
        } else if(fileType.equals("4")){// 银行流水
            saveMemberManage.setBankFlow(fileName);
            saveMemberManage.setBankFlowTime(LocalDateTime.now());
        } else{
            return R.fail("上传文件失败");
        }
        saveMemberManage.setUpdateBy(SecurityUtils.getUsername());
        memberManageService.saveOrUpdate(saveMemberManage);

        return R.ok(saveMemberManage, "上传文件成功");
    }


}
